package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page<DishDto>> getDishByPage(Integer page, Integer pageSize, String name) {

        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<Dish>();
        wrapper.like(name != null, Dish::getName, name);

        Page<Dish> dishPage=new Page<>(page, pageSize);
        dishService.page(dishPage, wrapper);
        List<Dish> dishList=dishPage.getRecords();

        List<DishDto> dishDtoList = new ArrayList<>();
        //将原有的数据 封装到新的增强数据模型
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            //根据 菜品所属的套餐id 查到套餐名
            Category category=categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        Page<DishDto> dishDtoPage = new Page<>();
        //将原有分页数据 传递给 新封装的数据模型
        BeanUtils.copyProperties(dishPage,dishDtoPage);
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    @PostMapping
    @CacheEvict(value="dishCache",key="#dishDto.categoryId")
    public R<String> addDish(@RequestBody DishDto dishDto) {
        boolean save=dishService.saveWithFlavor(dishDto);
        //添加菜品 清除缓存
        //redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return save ? R.success("添加菜品成功") : R.error("添加菜品失败");
    }

    @GetMapping("/{id}")
    public R<DishDto> getDishById(@PathVariable Long id) {
        DishDto dishDto=dishService.getDtoWithFlavorById(id);
        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value="dishCache",key="#dishDto.categoryId")
    public R<String> updateDish(@RequestBody DishDto dishDto) {
        boolean flag=dishService.updateWithFlavor(dishDto);
        //更新菜品 清除缓存
        //redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return flag ? R.success("修改菜品成功") : R.error("修改菜品失败");
    }

    @PostMapping("/status/{status}")
    public R<String> changeDishStatusByIds(@PathVariable Integer status, Long[] ids) {
        List<Dish> dishes=new ArrayList<>();
        for (Long id : ids) {
            Dish dish=new Dish();
            dish.setStatus(status);
            dish.setId(id);
            dishes.add(dish);
        }
        dishService.updateBatchById(dishes);
        return R.success("修改状态成功!");
    }

    @DeleteMapping
    public R<String> deleteDishByIds(@RequestParam List<Long> ids) {
        dishService.removeByIds(ids);
        return R.success("");
    }

    @GetMapping("/list")
    @Cacheable(value="dishCache",key="#categoryId")
    public R<List<DishDto>> getDishListByCategoryId(Long categoryId, Integer status,HttpSession session) {
        //获取缓存redis 的key  redisTemplate
        /*String key = "dish_"+categoryId+"_"+status;
        System.out.println(categoryId);
        List<DishDto> dishDtoList=(List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null){
            return R.success(dishDtoList);
        }*/

        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId).eq(status != null,Dish::getStatus,status);
        //根据套餐名 获取该套餐下 所有菜品
        List<Dish> list=dishService.list(wrapper);
        List<DishDto> dishDtoList = new ArrayList<>();
        //将菜品进行增强
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper=new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
            dishDto.setFlavors(dishFlavorService.list(flavorLambdaQueryWrapper));
            dishDtoList.add(dishDto);
        }

        //将列表放入缓存中 1小时失效
        //redisTemplate.opsForValue().set(key,dishDtoList,1, TimeUnit.HOURS);
        return R.success(dishDtoList);
    }
}
